const { parkingsModel } = require('./models/parkingsModel');
const {tenantsModel} = require('./models/tenantsModel');

//获取车位列表、分页、总计多少条数据
module.exports.getParkings = async function (val) {
    let totalNum = await parkingsModel.countDocuments();//获取总共有多少条数据
    
    const data = await parkingsModel
        .find({  [val.options]: { $regex: val.search_data, $options: '$i' }, delete: false})
        .limit(val.pageSize - 0)
        .skip((val.currentPage - 1) * val.pageSize)
        ;
    const parkingObj = {
        data: [],
        totalPage: 0,
        totalNum: 0,
        currentPage: val.currentPage - 0
    }
    parkingObj.data = data;
    parkingObj.totalPage = Math.ceil(totalNum / val.pageSize);//获取总共有多少页
    parkingObj.totalNum = totalNum;
    // 第二种方式{
    //     [stu.options]: { $regex: stu.search_data, $options: '$i' }
    // }
    // 如果stu是一个空对象的话，依然是搜索所有模块。

    return parkingObj;
}

//查询车位
module.exports.searchParkings = async function (val) {
    //筛选和搜索没有被用户删除的数据
    //这里的出租方id是暂时模拟
    const totalNum = (await parkingsModel.find({
        [val.options]: { $regex: val.search_data, $options: '$i' }, delete: false, 
        // lessorsid: "5fad03e8842d3427f8660183"
    })).length;
    //如果val是一个空对象的话，依然是搜索所有模块。
    const data = await parkingsModel.find({
        [val.options]: { $regex: val.search_data, $options: '$i' },delete: false,
        //  lessorsid: "5fad03e8842d3427f8660183"
    })
        .populate('tenantsId')
        .populate('lessorsId')

        //还差出租方的关联id
        //  .populate({
        //     path: 'lessorsId',
        //  })
        .limit(val.pageSize - 0)
        .skip((val.currentPage - 1) * val.pageSize)
        ;

    const parkingObj = {
        data: [],
        totalPage: 0,
        totalNum: 0,
        currentPage: val.currentPage - 0
    }

    parkingObj.data = data;
    parkingObj.totalPage = Math.ceil(totalNum / val.pageSize);//获取总共有多少页
    parkingObj.totalNum = totalNum;
    return parkingObj;

}


//确认修改数据modifyParkings
module.exports.modifyParkings = async function (val) {

    const data = await parkingsModel.updateOne({ _id: val._id }, {
        address: val.address,
        telephone: val.telephone,
        number: val.number,
        property: val.property,
        cycle: val.cycle,
        price: val.price
    });
    return data;
}

//删除前检验state值checkParkingsState

module.exports.checkParkingsState = async function (val) {
    const data = await parkingsModel.find(val);
    return data;
}
//删除车位searchParkings

module.exports.deleteParkings = async function (val) {
    //修改delete值，软删除，数据库里还是有数据
    const data = await parkingsModel.updateOne({ _id: val._id }, { delete: true });
    return data;
}

//添加车位 冰
module.exports.addParking = async function (val) {
    const data = await parkingsModel.create(val);
    return data;
}



//修改上下架的state 冰
module.exports.amendState = async function (val, num) {
    await parkingsModel.updateOne(val, { state: num });
}




